package com.api.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/*
    @ClassName FileUploadAndDownLoadUtill
    @Description TODO
    @Date 2021/7/20、19:29
*/
public class FileUploadAndDownLoadUtill {

    /*
     * @Author: XiaoDun
     * @Description:文件上传无BUG版
     * @Date: 2021/7/27 18:49
     * params file
     * return java.lang.String
     **/
    public static String uploadFile(MultipartFile file) {

        String filename = file.getOriginalFilename();
        String newFilePath = "C:\\Users\\XiaoDun\\AppData\\Local\\Temp\\tomcat.8912619798225703622.8001\\work\\Tomcat\\localhost\\ROOT\\img";

        try {
            if (file != null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(newFilePath+filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    String uploadUrl = AliyunOSSUtil.upLoad(newFile);

                    return "http://xiaodun.oss-cn-hangzhou.aliyuncs.com/"+uploadUrl;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /*
        根据文件所在路径下载文件
    */
    public static void download(HttpServletResponse response, String filePath) {
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));//文件名
            response.setHeader("Content-Length", String.valueOf(file.length()));
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void download(String filePath, HttpServletResponse responset) {
        AliyunOSSUtil.download(filePath, responset);
    }

}


